22. Exercise: Implement a Click Listener
L7 36 Implement A Click Listener SC
Now it’s your turn to complete this exercise yourself!
In this exercise you'll implement a ClickListener and bind it in the adapter.
In
SleepNightAdapter, create a new class calledSleepNightListener.The listener class receives a
SleepNightobject and passes itsnightIdfield:class SleepNightListener(val clickListener: (sleepId: Long) -> Unit) { fun onClick(night: SleepNight) = clickListener(night.nightId) }Wire up the new listener to class to your
list_item_sleep_night.xmlby creating new variable.<variable name="clickListener" type="com.example.android.trackmysleepquality.sleeptracker.SleepNightListener"/>In order to tell the view to call your click listener, add your click listener to onClick property of the ConstaintLayout.
android:onClick="@{() -> clickListener.onClick(sleep)}"
- Add a SleepNightListener reference to the SleepNightAdapter class declaration.
class SleepNightAdapter(val clickListener: SleepNightListener)
To finish the adapter, add clickListener to DataBinding in onBindViewHolder method.
Edit the call to holder.bind to pass the click listener:
holder.bind(clickListener,getItem(position)!!)
Following the prior step, pass the click listener to
bind()and add it to thebinding:fun bind(clickListener: SleepNightListener, item: SleepNight) { binding.sleep = item binding.clickListener = clickListener binding.executePendingBindings() }In
SleepTrackerFragment, fix the error on theadapter = SleepNightAdapter()declaration by passing theSleepNightListenerobject.Have the listener display the nightId in a toast message when the user clicks the item in the grid.
val adapter = SleepNightAdapter(SleepNightListener { nightId -> Toast.makeText(context, "${nightId}", Toast.LENGTH_LONG).show() })Build and run the code, and try out your new click listener!
If you want to start at this step, you can download this exercise from: Step.11-Exercise-Implement-a-Click-Listener.
You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.
Once you’re done, you can check your solution against the solution we’ve provided here: Step.11-Solution-Implement-a-Click-Listener, or using this git diff.
Task Description:
Complete the steps below to implement a ClickListener and bind it in the adapter.
Task Feedback:
A toast to you!